//
//  EcontractVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2021/7/23.
//  Copyright © 2021 zwb. All rights reserved.
//  电子合同

import UIKit
 
class ZyaEcontractVC: UITableViewController,UISearchBarDelegate {
     
    // MARK: - Getter And Setter
//    var startDate = Date.preMonths_1(3)
    var startDate = ""
    var endDate = Date.today
    private var searchBar:UISearchBar?

     var keyword = ""
    var auditMark = ""
    var page = 1
    fileprivate var dataArray = [ZyaESignModel]()
  
    // MARK: - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setSearchBar()
         tableView.register(ZyaEcontractCell.self, forCellReuseIdentifier: ZyaEcontractCell.identifier)
        
        let searchBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.search, target: self, action:#selector(searchAction))
        searchBtn.tintColor = .white
     
        self.navigationItem.rightBarButtonItems =  [searchBtn]
        self.tableView.mj_header = KSRefreshHeader {
            self.page = 1
            self.fetchData()
        }
        self.tableView.mj_footer = KSRefreshFooter {
            self.page += 1
            self.fetchData()
        }
        self.tableView.tableFooterView = UIView()
        self.tableView.mj_header?.beginRefreshing()
        
    }
   
    @objc func searchAction() {
        let alert = KSAlertView()
         let txt0 = alert.addCalendar(withLabel: "开始日期", action: nil)
        let txt1 = alert.addCalendar(withLabel: "结束日期", action: nil)
 
        txt0.text = self.startDate
        txt1.text = self.endDate
 
        _ = alert.addButton("查询") { [unowned self] in
             self.startDate =  txt0.text.unwrap
            self.endDate = txt1.text.unwrap
               self.tableView.mj_header?.beginRefreshing()
        }
        
        alert.show("查询条件", duration: 0.2, completeText: nil)
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.keyword = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    func setSearchBar () {
        searchBar = TenderSearchBar(frame:CGRect(x:0,y:0,width:KSGlobal.screenW * 0.65,height:40))
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        
        searchBar!.layer.cornerRadius = 15
        searchBar!.layer.masksToBounds = true
        
        
        if #available(iOS 13.0, *) {
            searchBar!.searchTextField.backgroundColor = .white
            searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
            searchBar!.searchTextField.font = UIFont.systemFont(ofSize: 14)

        } else {
            // Fallback on earlier versions
            let searchField = searchBar!.value(forKey: "searchField") as! UITextField
            searchField.backgroundColor = .white
            searchField.layer.cornerRadius = 18
            searchField.layer.masksToBounds = true
            searchField.font = UIFont.systemFont(ofSize: 14)

        }
     
        
        searchBar!.text = self.keyword
          searchBar!.placeholder = "请输入公司名称或合同编号"
        searchBar!.delegate = self
        let searchView = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW * 0.65 ,height:40))
        searchView.addSubview(searchBar!)
        self.navigationItem.titleView = searchView
   
    }
    
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    // MARK: - Public Method
    func fetchData() {
        
        KSNetwork.shared.doRequest(API.eSignControllerQuery(page: "\(page)", size: "\(KSGlobal.pageSize)", startDate: startDate, endDate: endDate, keyWord: keyword)) { [weak self]  (data:BaseResult<ZyaESignModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    let oriI = infos
                     let hts = oriI.compactMap { $0.sNo }.joined(separator: ",")
                    if hts == "" {
                        self.tableView.reloadData()
                        self.tableView.mj_header?.endRefreshing()
                        self.tableView.mj_footer?.endRefreshing()
                        if infos.count < KSGlobal.pageSize {
                            self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    } else {
                        // sno 拼接  取另外的值
                        KSNetwork.shared.doRequest(API.eSignQueryScale(z_ht_no: hts)) { (data:BaseResult<ZyaDzhtRateModel>) in
                            if data.flag == TRUE {
                                if let infos_s = data.infoArrCombine {
                                    for i in 0..<infos_s.count {
                                        oriI[i].inLibrary = infos_s[i].inLibrary
                                        oriI[i].payment = infos_s[i].payment
                                        
                                        oriI[i].out_library = infos_s[i].out_library
                                        oriI[i].invoice = infos_s[i].invoice
                                        oriI[i].contract = infos_s[i].contract
     
                                     }
     
                                    self.dataArray += oriI
                                    self.tableView.reloadData()
                                    self.tableView.mj_header?.endRefreshing()
                                    self.tableView.mj_footer?.endRefreshing()
                                    if infos.count < KSGlobal.pageSize {
                                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                                    }
                                }
                            } else {
                                KSToast(data.errorCombine.unwrap)
                            }
                        }
                    }

                    
                    
                    
                    
                    
                }
                
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
    }
    
}

// MARK: - Table view data source
extension ZyaEcontractVC {
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let one = dataArray[indexPath.row]
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaEcontractCell.identifier, for: indexPath) as? ZyaEcontractCell else {
            fatalError()
        }
        cell.selectionStyle = .none
        cell.one = one
        cell.statusBtn.addTouchUpInSideAction{ [indexPath] _ in
            KSNetwork.shared.doRequest(API.viewFile(flow_id: self.dataArray[indexPath.row].flowId.unwrap, org_code: self.dataArray[indexPath.row].orgCode.unwrap)) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                     let cwebV = CommonWebController(needEncode: false)
                    cwebV.reportUrl = data.infoStr.unwrap
                    cwebV.title = "合同签章"
                    self.navigationController?.pushViewController(cwebV, animated: true)
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
                
            }
            
        }
        cell.operateBtn.setTitle(["附件管理","付款明细","入库明细"])
        cell.operateBtn.clickAction = { [one,indexPath] indexx ,titlestr in
  
            
            if titlestr == "入库明细" {
                
                
                
                let vc = KSSingleSelectNetUtil(searchType:.none,tintColor:.white)
                vc.title = "入库明细"
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.eSignQueryLibrary(z_ht_no:one.sNo.unwrap)) { (data:BaseResult<ZyaEsLibraryModel>) in
                        if data.flag == TRUE {
                            if let infos = data.infos {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                }
                vc.kSSingleSelectNetShowCell = { cell,model in
                    
                    
                    var contArr:[(String,String?)]!
                     let modelx = (model as! ZyaEsLibraryModel)
                    
                  contArr = [
                               ("入库单号:","\(modelx.zNo.unwrap)")
                               ,("入库猪场:","\(modelx.zZcNm.unwrap)")
                               ,("入库仓库:","\(modelx.zStorageNm.unwrap)")
                               ,("入库日期:","\(modelx.zDate.unwrap)")
                               ,("数量:","\(modelx.zNumber.unwrap)\(modelx.zGoodsUnit.unwrap)")
                               ,("换算数量:","\(modelx.sNumber.unwrap)\(modelx.sGoodsUnit.unwrap)")
 
                           ]
                  cell.setDataSource(contentArr: contArr)
                 }
                
                self.navigationController?.pushViewController(vc,animated:true)
                
                
 
        
            }
            if titlestr == "付款明细" {
                
                
                let vc = KSSingleSelectNetUtil(searchType:.none,tintColor:.white)
                vc.title = "付款明细"
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.eSignQueryPay(z_ht_no:one.sNo.unwrap)) { (data:BaseResult<ZyaEsPayModel>) in
                        if data.flag == TRUE {
                            if let infos = data.infos {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                }
                vc.kSSingleSelectNetShowCell = { cell,model in
                    
                    
                    var contArr:[(String,String?)]!
                     let modelx = (model as! ZyaEsPayModel)
                    
                  contArr = [
                               ("付款单号:","\(modelx.no.unwrap)")
                               ,("付款金额:","\(modelx.money_cancel.unwrap)")
                               ,("付款日期:","\(modelx.in_date.unwrap)")
                               ,("出纳付款时间:","\(modelx.cn_dt.unwrap)")
                            ]
                  cell.setDataSource(contentArr: contArr)
                 }
                
                self.navigationController?.pushViewController(vc,animated:true)
                
               
            }
            if titlestr == "附件管理" {
                let vc = ZyaESignAssistFVC()
                vc.z_ht_no = one.sNo.unwrap
                vc.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc, animated: true)
 
            }
        }
        return cell
        
        
        
        
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//        let one = dataArray[indexPath.row]
//        let vc = HiddenTroubleForm(excuteType: .fix)
//        vc.model = one
//        vc.refreshClosure = {
//            self.tableView.mj_header?.beginRefreshing()
//        }
//        self.navigationController?.pushViewController(vc, animated: true)
    }
}
